package com.snopy.concurrency.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ABADemo
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/28 14:37
 */
@Slf4j
public class CoverABADemo {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A",0);
    public static void main(String[] args) throws InterruptedException {
        String prev = ref.getReference();
        int stamp = ref.getStamp();
        other();
        TimeUnit.MILLISECONDS.sleep(200);
        log.debug("change A->C:{}",ref.compareAndSet(prev,"C",stamp,stamp+1));
    }
    private static void other() throws InterruptedException {
        new Thread(()->{
            String prev = ref.getReference();
            int stamp = ref.getStamp();
            log.debug("change A->B:{}",ref.compareAndSet(prev,"B",stamp,stamp+1));
        },"t1").start();
        TimeUnit.MILLISECONDS.sleep(200);
        new Thread(()->{
            String prev = ref.getReference();
            int stamp = ref.getStamp();
            log.debug("change B->A:{}",ref.compareAndSet(prev,"A",stamp,stamp+1));
        },"t1").start();
    }
}
